package com.emperor.course.app;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Map;
import org.apache.log4j.Logger;

import org.apache.commons.lang.StringUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.hibernate.classic.Session;

import com.emperor.core.app.AppConstant;
import com.emperor.course.logic.Course;
import com.emperor.course.logic.CourseModel;
import com.emperor.course.logic.CourseProduct;
import com.emperor.course.logic.CourseProductModel;
import com.emperor.employee.logic.Employee;
import com.emperor.product.logic.Product;
import com.emperor.product.logic.ProductModel;
import com.emperor.transaction.logic.Transaction;
import com.emperor.user.logic.User;
import com.emperor.util.HibernateUtil;
import com.swtdesigner.SWTResourceManager;

public class CourseProdAppNew extends Dialog {
	protected Object result;
	protected Shell shlNewCourseProduct;
	protected Map<String, Object> params;

	private DecimalFormat df0, df2;
	private Text text;
	private Text txtCourseName;
	private Text txtProductName;

	private Course course = null;
	private Product product = null;

	public static Logger log = Logger.getLogger(CourseProdAppNew.class);

	public CourseProdAppNew(Shell parent, int style, Map<String, Object> params) {
		super(parent, style);
		this.params = params;
	}

	/**
	 * Create the dialog
	 * 
	 * @param parent
	 * @param style
	 */
	public CourseProdAppNew(Shell parent, int style) {
		super(parent, style);
	}

	/**
	 * Create the dialog
	 * 
	 * @param parent
	 */
	public CourseProdAppNew(Shell parent) {
		this(parent, SWT.NONE);
	}

	/**
	 * Open the dialog
	 * 
	 * @return the result
	 */
	public Object open() {
		createContents();
		shlNewCourseProduct.open();
		shlNewCourseProduct.layout();
		Display display = getParent().getDisplay();
		while (!shlNewCourseProduct.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		return result;
	}

	/**
	 * Create contents of the dialog
	 */
	protected void createContents() {

		df0 = new DecimalFormat();
		df0.applyPattern("##########.##");
		df0.setMinimumFractionDigits(0);
		df0.setMaximumFractionDigits(0);

		df2 = new DecimalFormat();
		df2.applyPattern("##########.##");
		df2.setMinimumFractionDigits(2);
		df2.setMaximumFractionDigits(2);

		shlNewCourseProduct = new Shell(getParent(), SWT.DIALOG_TRIM
				| SWT.APPLICATION_MODAL);
		shlNewCourseProduct.setBackgroundMode(SWT.INHERIT_DEFAULT);
		shlNewCourseProduct.setBackgroundImage(SWTResourceManager.getImage(
				CourseProdAppNew.class, "/img/main.jpg"));
		shlNewCourseProduct.setImage(SWTResourceManager.getImage(
				CourseProdAppNew.class, "/img/iMac OSX.png"));
		shlNewCourseProduct.setFont(SWTResourceManager
				.getFont("", 12, SWT.NONE));
		shlNewCourseProduct.setSize(500, 263);
		shlNewCourseProduct.setText("New Course Product");

		final Composite composite = new Composite(shlNewCourseProduct, SWT.NONE);
		composite.setBounds(0, 0, 494, 234);

		final Label quantityLabel = new Label(composite, SWT.NONE);
		quantityLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		quantityLabel.setText("Quantity");
		quantityLabel.setBounds(50, 131, 85, 20);

		final Button okButton = new Button(composite, SWT.NONE);
		okButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				doAdd(course, product, text, getParams());
				getShell().close();
			}
		});
		okButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		okButton.setImage(SWTResourceManager.getImage(CourseProdAppNew.class,
				"/img/Symbol-Check.png"));
		okButton.setText("OK");
		okButton.setBounds(173, 180, 119, 30);

		final Label customerDiscountWillLabel = new Label(composite, SWT.NONE);
		customerDiscountWillLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		customerDiscountWillLabel
				.setText("Enter the product quantity in the course.");
		customerDiscountWillLabel.setBounds(50, 30, 375, 20);

		Label productNameLabel = new Label(composite, SWT.NONE);
		productNameLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		productNameLabel.setBounds(51, 92, 119, 20);
		productNameLabel.setText("Product Name");

		Label courseNameLabel = new Label(composite, SWT.NONE);
		courseNameLabel.setText("Course Name");
		courseNameLabel.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont(
				"Segoe UI", 12, SWT.NORMAL));
		courseNameLabel.setBounds(51, 56, 119, 20);

		text = new Text(composite, SWT.BORDER);
		text.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		text.setBounds(173, 128, 238, 30);

		txtCourseName = new Text(composite, SWT.BORDER);
		txtCourseName.setEditable(false);
		txtCourseName.setToolTipText("course_name");
		txtCourseName.setBounds(173, 56, 238, 30);

		txtProductName = new Text(composite, SWT.BORDER);
		txtProductName.setToolTipText("product_name");
		txtProductName.setEditable(false);
		txtProductName.setBounds(173, 92, 238, 30);

		//
		centreShell(shlNewCourseProduct);
		populateControls(txtCourseName, txtProductName);

		Button closeButton = new Button(composite, SWT.NONE);
		closeButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				getShell().close();
			}
		});
		closeButton.setBounds(298, 180, 113, 30);
		closeButton.setImage(SWTResourceManager.getImage(
				CourseProdAppNew.class, "/img/Symbol-Delete.png"));
		closeButton.setFont(org.eclipse.wb.swt.SWTResourceManager.getFont("Segoe UI", 12, SWT.NORMAL));
		closeButton.setText("Close");

	}

	public void centreShell(Shell shell) {
		Rectangle pDisplayBounds = shell.getDisplay().getBounds();
		Rectangle pShellBounds = shell.getBounds();

		int nLeft = (pDisplayBounds.width - pShellBounds.width) / 2;
		int nTop = (pDisplayBounds.height - pShellBounds.height) / 2;

		shell.setBounds(nLeft, nTop, pShellBounds.width, pShellBounds.height);
	}

	public Map<String, Object> getParams() {
		return params;
	}

	public void setParams(Map<String, Object> params) {
		if (params != null) {
			this.params = params;
		}
	}

	public Shell getShell() {
		return shlNewCourseProduct;
	}

	private void populateControls(Text txtCourseName, Text txtProdName) {
		if (getParams().get(CourseAppCtrl.COURSE_ID) == null) {
			getParams().put(CourseAppCtrl.COURSE_MSG,
					"Unable to display course. Course ID not found.");

			getShell().close();
		}

		try {
			Session session = HibernateUtil.getSessionFactory()
					.getCurrentSession();
			session.beginTransaction();

			Long course_id = (Long) getParams().get(CourseAppCtrl.COURSE_ID);
			course = (Course) session.get(CourseModel.class, course_id);

			if (course != null && course.getId() != null) {
				txtCourseName.setText(course.getName());
			}

			Long prod_id = (Long) getParams().get(CourseAppCtrl.PROD_ID);
			product = (Product) session.get(ProductModel.class, prod_id);

			if (product != null && product.getId() != null) {
				txtProdName.setText(product.getName());
			}
		} catch (Exception e) {
			log.error("Unable to populate course product dialog.", e);
		}
	}

	private int doAdd(Course course, Product product, Text txtQuantity,
			Map<String, Object> params) {
		int rowCount = 0;
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		try {
			session.beginTransaction();

			CourseProduct courseProduct = new CourseProductModel();
			courseProduct.setProduct(product);
			courseProduct.setCourse(course);
			courseProduct.setQuantity(txtQuantity.getText());

			if (params.get(AppConstant.USER) != null) {
				User user = (User) params.get(AppConstant.USER);
				Employee employee = user.getEmployee();

				Date today = new Date();
				courseProduct.setStatus(AppConstant.STATUS_ACTIVE);
				courseProduct.setCrtby(employee.getId());
				courseProduct.setCrtdate(today);
				courseProduct.setUpdby(employee.getId());
				courseProduct.setUpddate(today);
			}

			session.save(courseProduct);
			rowCount++;
			log.debug(courseProduct.getClass().getSimpleName() + " : "
					+ courseProduct.getValues().toString());
			session.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
			log.error(e.getMessage(), e);
		}
		return rowCount;
	}
}
